<?php

class Registe extends Controller {
	public function html() {
		//已登录跳转到转入页面
		$mUser = new User_model();
		$currUser = $mUser->currUser();
		if($currUser) header('Location: '.($this->backurl()?$this->backurl():'/user/'));
		
		$data = array();$tpl = 'user/registe.html';
		$this->display($data, $tpl);
	}
	public function json() {
		$nickname = $this->post('nickname', 'str');
		$password = $this->post('password', 'str');
		$email = $this->post('email', 'str');
		$password1 = $this->post('password1', 'str');
		
		if(!$nickname) $this->displayJSON(array('status' => -1, 'message' => '请输入昵称'));
		if(Validate::length($nickname) < 4) $this->displayJSON(array('status' => -9, 'message' => '你输入的昵称不能小于4个字符'));
		if(Validate::length($nickname) > 30) $this->displayJSON(array('status' => -10, 'message' => '你输入的昵称不能大于30个字符'));
		
		if(!$password) $this->displayJSON(array('status' => -2, 'message' => '请输入密码'));
		if(Validate::length($password) <6) $this->displayJSON(array('status' => -11, 'message' => '你输入的密码长度不能小于6个字符'));
		
		if($password1 != $password) $this->displayJSON(array('status' => -3, 'message' => '两次输入密码不一致'));
		if(!$email) $this->displayJSON(array('status' => -4, 'message' => '请输入邮箱'));
		if(!Validate::isEmail($email)) $this->displayJSON(array('status' => -5, 'message' => '请输入正确格式的邮箱'));
		
		$cols = array(
			'nickname' => $nickname,
			'password' => $password,
			'email' => $email,
			'salt' => Func::randstr(6),
			'created_time' => Func::time(),
			'created_ip' => Func::clientIp(),
		);
		
		$mUser = new User_model();
		//判断邮箱是否存在
		$user = $mUser->userInfoByEmail($email);
		if($user) $this->displayJSON(array('status' => -6, 'message' => '邮箱已存在'));
		//判断昵称是否存在
		$user = $mUser->userInfoByNickname($nickname);
		if($user) $this->displayJSON(array('status' => -7, 'message' => '昵称已存在'));
		
		$uid = $mUser->create($cols);
		if(!$uid) $this->displayJSON(array('status' => -8, 'message' => '注册失败'));
		
		$data['user'] = $cols;unset($data['user']['password']);
		$data['user']['uid'] = $uid;
		$data['verify'] = Func::randstr(32); //验证码
		$content = $this->fetch($data, 'module/module_registe_email.html');
		
		//保存邮箱验证码
		$params = array(
			'verify' => $data['verify'],
			'email' => $data['user']['email'],
			'created_time' => Func::time(),
		);
		$result = $mUser->saveEmailVerify($params);
		if($result) {
			//注册成功发送邮件(添加到邮件发送队列)
			$mEmailQueue = new EmailQueue_model();
			
			$params = array(
				'type' => 1,
				'subject' => '您的越实惠账号信息',
				'content' => $content,
				'created_time' => Func::time(),				
			);
			$mEmailQueue->put($params);
		}
		$this->displayJSON(array('status' => 0, 'message' => '注册成功', 'user' => $data['user']));
		
	}
}